'We can create instance attrbitues for objects in Python. Can we create instance methods (not class Methods) as well in Python?
How To create a methods which are common to a particular object just like creating instance attrbitue obj.instance_attribute A method which belongs specifically for a single object ?
The link contains the code. I need to create method only for this object and not all instance of class. Creating class methods and attribute. The instance attrbitue. How to create instance methods
class A(): def init(self): self.class_variable = 999999 def class_methods(self): #available to all object print("Hey")
obj = A() obj.class_variable 999999 obj.class_methods() Hey obj.instance_attribute = 40404040 #common to particular object obj.instance_attribute 40404040 #a method which is common to only this object obj.new_method():
SyntaxError: invalid syntax
obj.new_mehtod(self):
SyntaxError: invalid syntax
Solution 1:[1]
I think you are mixing up terminology. Every "normal" method is a instance method - that means it applies the function without affecting any other instances of this class. To reference the instance, use the passed self keyword.
Defining a method for a single instance inside the generator/ class definition does not make sense in an OOP-context. If you create a car class, every instance of this class should be able to access its methods, like drive().
The only way to add a unique function is to add it after instantiating the object. This can be done with the types.MethodType method, which binds the function to the class instance:
from types import MethodType
def fly(self):
print(f"i, {self.name}, can fly")
class Car:
def __init__(self, name):
self.name = name
car_1 = Car("car one")
car_2 = Car("car two")
car_1.fly = MethodType(fly, car_1)
car_1.fly() # i, car one, can fly
car_2.fly() # AttributeError: 'Car' object has no attribute 'fly'
As you can see, car_1 has the class fly, which references car_1's name, while car_2 does not have this function.
But you should seriously reconsider what you are trying to achieve here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fogx |
