简体   繁体   English

在面向对象的python中访问变量和函数-python

[英]Accessing variable and functions in object oriented python - python

  1. How to I declare a default value in a python object? 如何在python对象中声明默认值?

Without a python object it looks fine: 没有python对象,看起来不错:

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

With a python object I get the following error: 使用python对象时,出现以下错误:

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: 使用python对象,出现错误:

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来定义类:

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() . 请注意,您需要参考self.xgetStuff()

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. 请注意,对于函数关键字参数default使用可变值通常不是一个好主意。 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 在python中定义一个类,你必须使用

    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():

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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