Hello im trying to make a chess game, however i cant seem to get this class to work, how to do i get the variable pawn_black1_status in the main block to change after i alter it in the class? If it works correctly it should print "dead"
class Status(object):
def __init__(self,piece,pawn_black1_status):
self.piece=piece
self.pawn_black1_status=pawn_black1_status
def Status2(self,piece,pawn_black1_status):
self.piece=piece
self.pawn_black1_status=pawn_black1_status
self.pawn_black1_status="dead"
pawn_black1_status="alive"
Pawn1b_status=Status("p1b",pawn_black1_status)
Pawn1b_status.Status2("p1b",pawn_black1_status)
print(pawn_black1_status)
You must reference the class you have created to access the variable within it.
class Status(object):
def __init__(self,piece,pawn_black1_status):
self.piece=piece
self.pawn_black1_status=pawn_black1_status
def Status2(self,piece,pawn_black1_status):
self.piece=piece
self.pawn_black1_status=pawn_black1_status
self.pawn_black1_status="dead"
pawn_black1_status="alive"
Pawn1b_status=Status("p1b",pawn_black1_status)
Pawn1b_status.Status2("p1b",pawn_black1_status)
print(Pawn1b_status.pawn_black1_status)
Related
I run those code in Python online, but get the error message 'File "", line 1, in
NameError: name 'Account' is not defined'; I wonder how I could define "Account" there? thanks a lot! This is my first Python code.
class SavingAccount(Account):
def _init_(self, holder_name, saving_rateaccount_number=None):
super()._init_(holder_name, account_number)
self.saving_rate = saving_rate
def _repr_(self):
return 'SavingAccount('+str(self.holder_name)+', '+str(self.saving_rate)+', '+str(self.account_number)+')'
saving_account=SavingAccount('saving_1', 0.02)
print(saving_account)
If you define the class Account in another Python file, you have to have from other_file import Account before class SavingAccount(Account): to make it work.
When you do:
class My_class ( Other_class ):
def __init__(self,...):
# code lines
def my_method(self,...):
# more code
It means that My_class object will inherit Other_class methods and atributes, so you will have to define Other_class before in order to use it in My_class. In conclusion the new class will have it's own methods and atributes and also Other_class methods and atributes.
Example:
class Other_class():
def __init__(self,...):
# constructor code lines
def other_method(self,...):
# more code lines
class My_class( Other_class ):
def __init__(self,...):
# other constructor code lines
def my_method(self,...):
# some more code lines
You can find the full information in Python documentation.
PS: my recomendation is to always see the official documentation, you can even discover more thinks and expand you knowledge on the language. By the way you will see how useful is Python, keep it up 😁
I am new to python and asking very basic question. I am trying to understand multiple inheritance. I have two parent classes i.e Speciy and Living and one child class Bird but when i run the following program, i get error 'Bird' object has no attribute '_Living__house'.Please tell me what i am doing wrong
But when i use single inheritance i.e class Bird(Speciy) or class Bird(Living)it works fine. So only the error comes when i use multiple inheritence
class Speciy:
def __init__(self,legs=4,colour="White"):
self.__legs=legs
self.__colour=colour
def get_legs(self):
return self.__legs
def set_legs(self,legs):
self.__legs=legs
def get_colour(self):
return self.__colour
def set_colour(self,colour):
self.__colour=colour
class Living:
def __init__(self,house="city"):
self.__house=house
def get_house(self):
return self.__house
def set_house(self,house):
self.__house=house
class Bird(Speciy,Living):
def __init__(self,wings=2):
super().__init__()
super().__init__()
self.__wings=wings
def get_wings(self):
return self.__wings
def set_wings(self,wings):
self.__wings=wings
b1=Bird(4)
print(b1.get_wings())
b1.set_colour("Green")
print(b1.get_colour())
print(b1.get_house())
I have solved the issue my self using
Speciy.__init__(self,legs,colour)
Living.__init__(self,house)
I created the following class:
import loader
import pandas
class SavTool(pd.DataFrame):
def __init__(self, path):
pd.DataFrame.__init__(self, data=loader.Loader(path).data)
#property
def path(self):
return path
#property
def meta_dict(self):
return loader.Loader(path).dict
If the class is instantiated the instance becomes a pandas DataFrame which I wanted to extend by other attributes like the path to the file and a dictionary containing meta information (called 'meta_dict').
What I want is the following: the dictionary 'meta_dict' shall be mutable. Namely, the following should work:
df = SavTool("somepath")
df.meta_dict["new_key"] = "new_value"
print df.meta_dict["new_key"]
But what happens is that every time I use the syntax 'df.meta_dict' the method 'meta_dict' is called and the original 'meta_dict' from loader.Loader is returned such that 'df.meta_dict' cannot be changed. Therefore, the syntax leads to "KeyError: 'new_key'". 'meta_dict' shall be called only once and then never again if it is used/called a second/third... time. The second/third... time 'meta_dict' should just be an attribute, in this case a dictionary.
How can I fix this? Maybe the whole design of the class is bad and should be changed (I'm new to using classes)? Thanks for your answers!
When you call loader.Loader you'll create a new instance of the dictionary each time. The #property doesn't cache anything for you, just provides a convenience for wrapping complicated getters for a clean interface for the caller.
Something like this should work. I also updated the path variable so it's bound correctly on the class and returned in the path property correctly.
import loader
import pandas
class SavTool(pd.DataFrame):
def __init__(self, path):
pd.DataFrame.__init__(self, data=loader.Loader(path).data)
self._path = path
self._meta_dict = loader.Loader(path).dict
#property
def path(self):
return self._path
#property
def meta_dict(self):
return self._meta_dict
def update_meta_dict(self, **kwargs):
self._meta_dict.update(kwargs)
Another way to just cache the variable is by using hasattr:
#property
def meta_dict(self):
if not hasattr(self, "_meta_dict"):
self._meta_dict = loader.Loader(path).dict
return self._meta_dict
I am trying to create a class which takes a URL and allows me to split it into parts and return each of the scheme, server, and path.
class SimpleURL:
def __init__(self,url):
self.url=url
def scheme(self):
return url.split("://")[0]
def server(self):
return url.split("/")[2]
def path(self):
return url.split(url.split("/")[2])[1]
test_url = SimpleURL("https://gumgoose.com/larry/friendo")
Then, if I run
test_url.scheme()
or any server or path, I get the error
NameError: name 'url' is not defined
I am able to make it work if I assign the url to the variable "url" outside of the function, but to my understanding, the line beginning "test_url" should be doing that for me.
Can anybody shed some light onto this for me?
Within all of your class methods, you will need to explicitly use self to refer to all other class methods and attributes.
def scheme(self):
return self.url.split('://')[0]
If you do not do this, Python will only search the local scope within your method and the global scope. That is why if you define url outside of your class, you don't have any issues.
Python requires you reference the instance object too i.e.
return self.url.split('://')[0]
I don't understand how I am supposed to create static method, which will be run and called only once and which generates some output which will be used be other methods. For example:
class Player():
#staticmethod
def generateCardDeck():
deck = someCalculations
def someOtherMethod(self):
something = deck
def main():
Player.generateCardDeck()
if __name__ == '__main__':
main()
Is not going to work, I get error: NameError: global name 'deck' is not defined. But if I don't use static method, then how do I create multiple instances of the class, without running that method more than once (considering that other class methods would call generatedDeck() method)?
you can return the deck and use it wherever you want ... or you could make it a classmethod instead
class Player():
#classmethod
def generateCardDeck(cls):
cls.deck = someCalculations
Player.generateCardDeck()
print Player.deck
I suppose you could do roughly the same with static method
class Player():
#staticmethod
def generateCardDeck():
Player.deck = someCalculations
Player.generateCardDeck()
print Player.deck