Jerry Gao
Jerry Gao

Reputation: 1429

python class namespace and init function

class Complex:
     realpart,imagpart=0,0
     def __init__(self):
          self.r = Complex.realpart
          self.i = Complex.imagpart

x = Complex()

the above code works, x.r,x.i = (0,0), but when the class name is big, Class_name.Data_member way of accessing class data looks very redundant, is there any way to improve the class scoping, so I don't have to use Complex.imagpart? just use self.r = realpart?

Upvotes: 1

Views: 813

Answers (2)

Jake
Jake

Reputation: 2625

This is what you want to do:

class Complex(object):
    def __init__(self, realpart=0, imagpart=0):
        self.realpart = realpart
        self.imagpart = imagpart

Accessing the member variables is the "self.realpart" call. What you were using is class attributes which are accessed like this:

Complex.some_attribute

Upvotes: 1

Michael Mior
Michael Mior

Reputation: 28752

No. The data members you specified above are attributes of the class, and therefore require the class name to be specified. You could use self.r = self.__class__.realpart if you prefer. It seems as though you're just using these values as initializers though, so having realpart and imagpart at all is redundant.

(Also, note that Python has native support for complex numbers. Just write them such as 5+3j.)

Upvotes: 0

Related Questions