Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to use First Class Object Constructor value In another Object

Tags:

python

class MyClass(Object):

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

Now I have two objects

my_class1 = MyClass(x)

my_class2 = MyClass()

I want to use x when this my_class2 object is called

As other languages Support static variable like java,c++ etc.

like image 258
Ch Zeeshan Avatar asked Jul 27 '12 11:07

Ch Zeeshan


2 Answers

Assign it as 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
like image 146
Tadeck Avatar answered Sep 27 '22 23:09

Tadeck


There are no static variables in Python, but you can use the class variables for that. 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 looks first for instance-level variable, instantiated as self.x, and if not found - then looks for Class.x. So you can define it on class level, but override it on instance level.

A widely-used example is to use a default class variable with possible override into 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
like image 42
Tisho Avatar answered Sep 28 '22 01:09

Tisho