python
class MyClass:
my_class_var = "This is a class variable"
Instance Methods: are functions that belong to a specific instance of a class. They can access and modify the state of the object they belong to. To define an instance method, use the def
keyword inside the class definition.
```python
class MyClass:
my_class_var = "This is a class variable"
def instance_method(self):
print(self.my_class_var)
- **Class Methods**: are functions that operate on the class itself, rather than on an individual instance. They can be called without creating an instance of the class. To define a class method, use the `@classmethod` decorator.
python
class MyClass:
my_class_var = "This is a class variable"
@classmethod
def class_method(cls):
print(cls.my_class_var)
- **Static Methods**: are functions that don't have access to `self` or the class instance. They can be called without creating an instance of the class and do not interact with any instance variables. To define a static method, use the `@staticmethod` decorator.
python
class MyClass:
@staticmethod
def static_method():
print("This is a static method")
```
Creating and using class variables and methods:
```python
class MyClass:
my_class_var = "This is a class variable"
def init(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}!")
@classmethod
def from_string(cls, name_str):
return cls(name_str)
person1 = MyClass("Alice")
person2 = MyClass.from_string("Bob")
print(MyClass.my_class_var) # prints: This is a class variable
person1.greet() # prints: Hello, Alice!
```
What causes it: Attempting to access a class variable or method before the class has been defined.
print(MyClass.my_class_var) # Before defining MyClass
Error message:
NameError: name 'MyClass' is not defined
Solution: Ensure that the class has been defined before accessing its variables or methods.
MyClass = ... # Define MyClass first
print(MyClass.my_class_var) # Then access it
Why it happens: Python raises NameError when it cannot find a name in the current scope. In this case, the class has not been defined yet.
How to prevent it: Always define your classes before using them elsewhere in your code.
What causes it: Calling an instance method as if it were a function (without self
).
MyClass.instance_method() # Without an instance of MyClass
Error message:
TypeError: instance_method() missing 1 required positional argument: 'self'
Solution: Create an instance of the class and call the method using that instance.
person = MyClass("Alice")
person.instance_method()
Why it happens: Instance methods are bound to the instance they belong to, requiring self
as a parameter when called.
How to prevent it: Always use an instance of the class when calling instance methods.
self
as a parameter when called.self
.