Python: how to use the constructor value of a first class object In another object

class MyClass(Object): def __init__(self, x=None): if x: self.x = x def do_something(self): print self.x 

I now have two objects

my_class1 = MyClass(x)

my_class2 = MyClass()

I want to use x when this my_class2 object is called

Like other languages ​​Supports a static variable like java, C ++, etc.

+6
source share
3 answers

Assign it as a property to the class:

 >>> class MyClass(object): def __init__(self, x=None): if x is not None: self.__class__.x = x def do_something(self): print self.x # or self.__class__.x, to avoid getting instance property >>> my_class1 = MyClass('aaa') >>> my_class2 = MyClass() >>> my_class2.do_something() aaa 
+4
source

There are no static variables in Python, but you can use class variables for this. Here is an example:

 class MyClass(object): x = 0 def __init__(self, x=None): if x: MyClass.x = x def do_something(self): print "x:", self.x c1 = MyClass() c1.do_something() >> x: 0 c2 = MyClass(10) c2.do_something() >> x: 10 c3 = MyClass() c3.do_something() >> x: 10 

When you call self.x , it first looks for the instance level variable created as self.x , and if it is not found, it looks for Class.x . That way you can define it at the class level, but override it at the instance level.

A widely used example is the use of a default class variable with possible overriding into an instance:

 class MyClass(object): x = 0 def __init__(self, x=None): self.x = x or MyClass.x def do_something(self): print "x:", self.x c1 = MyClass() c1.do_something() >> x: 0 c2 = MyClass(10) c2.do_something() >> x: 10 c3 = MyClass() c3.do_something() >> x: 0 
+3
source

You can not. Instead, you can use the class attribute:

 class Klass: Attr = 'test' # access it (readonly) through the class instances: x = Klass() y = Klass() x.Attr y.Attr 

Learn more about Python classes.

0
source

Source: https://habr.com/ru/post/921482/


All Articles