pythonpython-3.xclasssetattrclass-attributes

How can i add atrributes to the class method from outside class?


This is gonna be my first question on this website. If I do mistake about English, sorry. Okey, my question is how can I add or set attribute to the class method from outside class?

If i am not wrong,we use settatr() to do this. Can you guys help me pls?

class sss():
   def __init__(self,name,surname):
       self.name = name
       self.surname = surname
   def method1(self):
       a = "Python"

When we do this:

object = sss("Adam","Roger") #This 2 lines are on outside the class
setattr(object,"Age",19)

What exactly happens? Now this "Age" attribute belong to our object? What is the value of the "Age" attribute now? I mean is that class attribute or what?

My second question is how can I add attribute to the class method?

Thank you


Solution

  • As @Julian Fock mentioned, you can add attributes to an object by simply writing statements, such as person.age = 19. Your instance/object of the sss-Person class would now have this attribute, but not the class itself.

    To modify the class sss-Person itself, you would need to implement some ugly methods, which would be labelled as "hacky" or "bad practices" by most programmers. Companies could refuse to accept the code as valid. You should instead consider using other methods such as class inheritance, where you can derive a modified class adding more advanced functionality.

    Still, changing a class definition can be useful for debugging or exceptional emergencies. In that case, you can define external functions, and link them to override your class methods as follows:

    # A) Initial Analysis
    
    class Person:
       def __init__(self,name,surname):
           self.name    = name
           self.surname = surname
       def method1(self):
           a = "Python"
    
    person1 = Person("Adam","Roger")
    person2 = Person("Adam","Roger")
    
    person1.age = 19
    
    print(person1.age)
    # Output: 19
    
    # print(person2.age)
    # AttributeError: 'Person' object has no attribute 'age'
    
    # B) Change class attributes
    
    def __init2__(self, name, surname, age):
        self.name    = name
        self.surname = surname
        self.age     = age
    
    Person.__init__ = __init2__
    
    person3 = Person("Adam","Roger", 20)
    
    print(person3.age)
    # Output: 20
    
    # person4 = Person("Adam","Roger")
    # TypeError: __init2__() missing 1 required positional argument: 'age'
    
    
    # C) Overwrite method1
    
    def method2(self):
        self.a = "Python"
    
    Person.method1 = method2
    
    person5 = Person("Adam","Roger",44)
    person5.method1()
    print(person5.a)
    # Output: "Python"