Python calling method in class

前端 未结 3 1342
予麋鹿
予麋鹿 2020-12-07 17:04

I\'m punching way above my weight here, but please bear with this Python amateur. I\'m a PHP developer by trade and I\'ve hardly touched this language before.

What I

3条回答
  •  天涯浪人
    2020-12-07 17:17

    Let's say you have a shiny Foo class. Well you have 3 options:

    1) You want to use the method (or attribute) of a class inside the definition of that class:

    class Foo(object):
        attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
        def __init__(self):
            self.attribute2 = 2          # instance attribute (those are accessible via first
                                         # parameter of the method, usually called 'self'
                                         # which will contain nothing but the instance itself)
        def set_attribute3(self, value): 
            self.attribute3 = value
    
        def sum_1and2(self):
            return self.attribute1 + self.attribute2
    

    2) You want to use the method (or attribute) of a class outside the definition of that class

    def get_legendary_attribute1():
        return Foo.attribute1
    
    def get_legendary_attribute2():
        return Foo.attribute2
    
    def get_legendary_attribute1_from(cls):
        return cls.attribute1
    
    get_legendary_attribute1()           # >>> 1
    get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
    get_legendary_attribute1_from(Foo)   # >>> 1
    

    3) You want to use the method (or attribute) of an instantiated class:

    f = Foo()
    f.attribute1                         # >>> 1
    f.attribute2                         # >>> 2
    f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
    f.set_attribute3(3)
    f.attribute3                         # >>> 3
    

提交回复
热议问题