I am pretty new to Python world and trying to learn it.
This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
def showName():
print carName
a = Car("bmw")
a.showName()
derived from object for new-style class
use __init__ to initialize the new instance, not __self__
__main__ is helpful too.
class Car(object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
def main():
a = Car("bmw")
a.showName()
if __name__ == "__main__":
main()
You don't define a variable, and you use init and self.
Like this:
class Car(Object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
a = Car("bmw")
a.showName()
this is not correct!
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
the first carName is a class Variable like static member in c++
the second carName (self.carName) is an instance variable,
if you want to set the class variable with the constructor you have to do it like this:
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
Car.carName = input
Related
I want to take advantage of polymorphism where the class that should be used for a certain action is defined in the database. Basically I want something that can work like this:
class Example:
#staticmethod
def do_something():
# Does something
s = "Example"
# Do magic here that makes s reference the class instead of just being a string
s.do_something()
Obviously, there probably needs to be some code to check it actually is a class that's defined and all that.
You can check if the class name exists in globals():
class Example:
#staticmethod
def do_something():
print("Hello from ExampleClass")
li = ["Example", "WrongExample"]
for cls in li:
if cls in globals():
print(f"Calling class {cls}:")
globals()[cls]().do_something()
else:
print(f"Class {cls} does not exists.")
# Calling class Example:
# Hello from ExampleClass
# Class WrongExample does not exists.
How do I use the function in the class below in the other class without using global?
Code:
class one:
class one_one:
def add(x):
return x+1
class one_two:
ans = one.one_one.add(1)
It certainly is an unusual design, but it will work if you remember to distinguish between classes and instances of classes (objects). In your example you are attempting to call add in the class one_one which is an instance method without first instantiating an object of that class type. The example below shows one way to achieve what you are trying to do by instantiating the objects before calling their methods.
Example:
class one:
class one_one:
def add(self, x):
return x+1
class one_two:
def add(self):
a_one_one = one.one_one()
ans = a_one_one.add(1)
return ans
a_one_two = one.one_two()
print(a_one_two.add())
Output:
2
I'm trying to create a subclass in a particular case and I can not attach attributes or method to it. I think the new / init usage is not clear to me but I could not find ways to do that from the internet.
Here is a minimal working toy example showing what I am trying to do.
---- Edit of create_special_human() function
# I have this
class Human():
def __init__(self):
self.introduction = "Hello I'm human"
def create_special_human():
special_human = do_very_complicated_stuffs() #returns type Human
special_human.introduction = "Hello I'm special"
return special_human
# I want to create this class
class SuperHero(Human):
def __new__(self):
special_human = create_special_human()
return special_human
def __init__(self):
self.superpower = 'fly'
def show_off(self):
print(self.introduction)
print(f"I can {self.superpower}")
human = Human()
special_human = create_special_human()
super_hero = SuperHero()
super_hero.show_off() # fails with error "type object 'Human' has no attribute 'show_off'"
print(super_hero.superpower) # fails with error "type object 'Human' has no attribute 'superpower'"
I want to create the subclass Superhero, and I need to initialize it with what is returned by create_special_human(), because this function is very complex in the real case. Moreover, I can not modify the Human class and create_special_human().
I am aware that the returned type is Human, which is wrong, but I don't know why that happens.
(Edited)
I've made few changes to your code and it is executing successfuly.
You must call superclass __init__ inside of a subclass __init__:
As I said in the comment, simply return SuperHero from create_special_human.
I've removed __new__ method from SuperHero since it doesn't make any sense. Take a look at this article
class Human():
def __init__(self):
self.introduction = "Hello I'm human"
class SuperHero(Human):
# Removed __new__
def __init__(self):
super().__init__() # Init superclass
self.superpower = 'fly'
def show_off(self):
print(self.introduction)
print(f"I can {self.superpower}")
def create_special_human():
# Simply initialize and return SuperHero instance
special_human = SuperHero()
do_very_complicated_stuffs(special_human)
special_human.introduction = "Hello I'm special"
return special_human
human = Human()
special_human = create_special_human()
super_hero = SuperHero()
super_hero.show_off()
print(super_hero.superpower)
You can read more about super() in this question.
Hi everyone i wanna use a calculated value from a method of the class itself for the rest of the class methods but it must calculate once for all and i need to invoke method inside the class itself i write an example:
class something():
def __init__():
pass
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
# I need to calculate summation here once for all:
# how does the syntax look likes, which one of these are correct:
something.__sum(1, 2)
self.__sum(1, 2)
# If none of these are correct so what the correct form is?
# For example print calculated value here in this method:
def do_something_with_summation(self):
print(self.summation)
Something like this seems to be what you're looking for:
class Something:
def __init__(self):
self.__sum(1, 2)
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
Not saying this is the ideal approach or anything, but you haven't really given us much to go off of.
In general, make sure self is the first argument in all class methods, and you can call that class method at any time using either self.method_name() if you are using it from within another class method or instance.method_name() if you're using it externally (where instance = Something()).
Assuming that you would receive variable1 and variable2 when you instantiate the class one solution could be:
class something():
def __init__(self, variable1, variable2):
self.summation = variable1 + variable2
def do_something_with_summation(self):
print(self.summation)
If instead you're creating variable1 and variable2 inside other methods, then you could make them class variables:
class Something():
def __init__(self):
#Put some initialization code here
def some_other_method(self):
self.variable1 = something
self.variable2 = something
def sum(self):
try:
self.summation = self.variable1 + self.variable2
except:
#Catch your exception here, for example in case some_other_method was not called yet
def do_something_with_summation(self):
print(self.summation)
I have a model where I want to use a class method to set the default of for a property:
class Organisation(db.Model):
name=db.StringProperty()
code=db.StringProperty(default=generate_code())
#classmethod
def generate_code(cls):
import random
codeChars='ABCDEF0123456789'
while True: # Make sure code is unique
code=random.choice(codeChars)+random.choice(codeChars)+\
random.choice(codeChars)+random.choice(codeChars)
if not cls.all().filter('code = ',code).get(keys_only=True):
return code
But I get a NameError:
NameError: name 'generate_code' is not defined
How can I access generate_code()?
As I said in a comment, I would use a classmethod to act as a factory and always create you entity through there. It keeps things simpler and no nasty hooks to get the behaviour you want.
Here is a quick example.
class Organisation(db.Model):
name=db.StringProperty()
code=db.StringProperty()
#classmethod
def generate_code(cls):
import random
codeChars='ABCDEF0123456789'
while True: # Make sure code is unique
code=random.choice(codeChars)+random.choice(codeChars)+\
random.choice(codeChars)+random.choice(codeChars)
if not cls.all().filter('code = ',code).get(keys_only=True):
return code
#classmethod
def make_organisation(cls,*args,**kwargs):
new_org = cls(*args,**kwargs)
new_org.code = cls.generate_code()
return new_org
import random
class Test(object):
def __new__(cls):
cls.my_attr = cls.get_code()
return super(Test, cls).__new__(cls)
#classmethod
def get_code(cls):
return random.randrange(10)
t = Test()
print t.my_attr
You need specify the class name: Organisation.generate_code()