AttributeError: type object x has no attribute y and some other inconsistencies with Python 3.4

AttributeError: type object x has no attribute y and some other inconsistencies with Python 3.4

我正在学习 Python 类 和 meta类。

下面是从文章 "Metaclasses Demystified" at the now-defunct website cleverdevil.org.

修改而来的示例
# metaclass methods

class Meta(type):
    def show(cls):
        return 'I am a Meta class method'

class Mistake(object):
    __metaclass__ = Meta

但是我遇到这个打印语句的错误:

>>> print(Mistake.show())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Mistake' has no attribute 'show'

下面是同类的另一个例子。

# data hiding
class Fruit:
    __price = 0

    def show(self):
        self.__price += 1
        print (self.__price)

objFruit = Fruit()
objFruit.show()
objFruit.show()
objFruit.show()
print (objFruit._Fruit.__price) # error

此外,我收到 print 'hello' 的错误,但 print('hello') 有效。

我不明白所有这些事情背后的背景。

您遇到三个不同的问题:

  1. 元类语法是 different in Python 2.x and 3.x:

    PEP 3115: New Metaclass Syntax. Instead of:

    class C:
        __metaclass__ = M
        ...
    

    you must now use:

    class C(metaclass=M):
        ...
    

    The module-global __metaclass__ variable is no longer supported. (It was a crutch to make it easier to default to new-style classes without deriving every class from object.)

  2. 您的代码导致的错误如下所示:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'Fruit' object has no attribute '_Fruit'
    

    ...不难理解:你的Fruit对象objFruit没有属性_Fruit。双下划线名称修饰 doesn't work the way you appear to think。这有效:

    print(objFruit._Fruit__price)  # no period
    
  3. 在Python3、print is a function.

注意:碰巧你在这个问题中提出的三个独立的问题解决起来相当微不足道,但一般来说,如果你有不止一个问题,你应该ask about each in a separate question.