class Person: def __init__(self, name): self.name = name def greet(self): return f"Hello, my name is {self.name}!"
person = Person("John") print(person.name) # Output: John print(person.greet()) # Output: Hello, my name is John!
John Hello, my name is John!
class Person: def __init__(self, name): self.__name = name def __greet(self): return f"Hello, my name is {self.__name}!"
person = Person("John") print(person.__name) # Error: AttributeError: 'Person' object has no attribute '__name' print(person.__greet()) # Error: AttributeError: 'Person' object has no attribute '__greet'
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[4], line 2 1 person = Person("John") ----> 2 print(person.__name) # Error: AttributeError: 'Person' object has no attribute '__name' 3 print(person.__greet()) # Error: AttributeError: 'Person' object has no attribute '__greet' AttributeError: 'Person' object has no attribute '__name'
class Person: def __init__(self, name): self._name = name def _greet(self): return f"Hello, my name is {self._name}!" class Student(Person): def study(self): return f"{self._name} is studying!"
student = Student("Alice") print(student._name) # Output: Alice print(student._greet()) # Output: Hello, my name is Alice! print(student.study()) # Output: Alice is studying!
Alice Hello, my name is Alice! Alice is studying!