简体   繁体   中英

Using an attribute as argument of a method of the same class

I want to define an attribute of a class and then use it as argument of a method in the same class in the following way

class Class1:
    def __init__(self,attr):
        self.attr=attr
    def method1(self,x=self.attr):
        return 2*x


It returns an error: NameError: name 'self' is not defined

How can I define the method in such a way that whenever I don't write x explicitly it just uses the attribute attr ?

In the example, what I mean is that I would like to have

cl=Class1()
print cl.method1(12) # returns '24'
cl.attr= -2
print cl.method1() # returns '-4'

This is because in method1, you just define the self variable in the first argument. And the self variable will only useable in the function body. You probably think self is a special keyword. Actually self is just anormal varialbe like any variable else.

To solve the issue: Use default value in function defination and check it in the function body:

class Class1:
    def __init__(self):
        self.attr = 3

    def method1(self, x=None):
        x = self.attr if x is None else x
        return 2*x


cl = Class1()
print(cl.method1(12))
cl.attr=-2
print(cl.method1())

Result:

24
-4

In your code it seems like you are naming x as an argument you are passing to the function when in reality you are giving the init function the value, try the following code:

class Class1:
    def __init__(self,attr = 3):
        self.attr=attr
    def method1(self):
        y = (self.attr)*(2)
        return y

When you call the function you should do it like this:

result = Class1(4)
print(result.method1())

>>8

PT Im kind of new in Python so don't give my answer for granted or as if it's the best way to solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM