简体   繁体   中英

Accessing variable and functions in object oriented python - python

  1. How to I declare a default value in a python object?

Without a python object it looks fine:

def obj(x={123:'a',456:'b'}):
    return x
fb = obj()
print fb

With a python object I get the following error:

def foobar():
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self,field):
        return x[field]
fb = foobar()
print fb.x

Traceback (most recent call last):
  File "testclass.py", line 9, in <module>
    print fb.x
AttributeError: 'NoneType' object has no attribute 'x'
  1. How do I get the object to return the value of a variable in the object?

With a python object, I got an error:

def foobar():
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self,field):
        return x[field]

fb2 = foobar({678:'c'})
print fb2.getStuff(678)

Traceback (most recent call last):
  File "testclass.py", line 8, in <module>
    fb2 = foobar({678:'c'})
TypeError: foobar() takes no arguments (1 given)

You didn't define a class, you defined a function with nested functions.

def foobar():
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self,field):
        return x[field]

Use class to define a class instead:

class foobar:
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self, field):
        return self.x[field]

Note that you need to refer to self.x in getStuff() .

Demo:

>>> class foobar:
...     def __init__(self,x={123:'a',456:'b'}):
...         self.x = x
...     def getStuff(self, field):
...         return self.x[field]
... 
>>> fb = foobar()
>>> print fb.x
{456: 'b', 123: 'a'}

Do note that using a mutable value for a function keyword argument default is generally not a good idea. Function arguments are defined once , and can lead to unexpected errors, as now all your classes share the same dictionary.

See "Least Astonishment" and the Mutable Default Argument .

to define a class in python you have to use

    class classname(parentclass):
        def __init__():
            <insert code>

With your code you're declaring a method not a class

Use

class foobar:

instead of

def foobar():

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