“Programm zur Demonstration der Kapselung in Python” Code-Antworten

Programm zur Demonstration der Kapselung in Python

# Python program to
# demonstrate protected members
 
# Creating a base class
class Base:
    def __init__(self):
 
        # Protected member
        self._a = 2
 
# Creating a derived class
class Derived(Base):
    def __init__(self):
 
        # Calling constructor of
        # Base class
        Base.__init__(self)
        print("Calling protected member of base class: ",
              self._a)
 
        # Modify the protected variable:
        self._a = 3
        print("Calling modified protected member outside class: ",
              self._a)
 
 
obj1 = Derived()
 
obj2 = Base()
 
# Calling protected member
# Can be accessed but should not be done due to convention
print("Accessing protedted member of obj1: ", obj1._a)
 
# Accessing the protected variable outside
print("Accessing protedted member of obj2: ", obj2._a)
mathiasgodwin

Programm zur Demonstration der Kapselung in Python

# Python program to
# demonstrate private members
 
# Creating a Base class
 
 
class Base:
    def __init__(self):
        self.a = "GeeksforGeeks"
        self.__c = "GeeksforGeeks"
 
# Creating a derived class
class Derived(Base):
    def __init__(self):
 
        # Calling constructor of
        # Base class
        Base.__init__(self)
        print("Calling private member of base class: ")
        print(self.__c)
 
 
# Driver code
obj1 = Base()
print(obj1.a)
 
# Uncommenting print(obj1.c) will
# raise an AttributeError
 
# Uncommenting obj2 = Derived() will
# also raise an AtrributeError as
# private member of base class
# is called inside derived class
mathiasgodwin

Programm zur Demonstration der Kapselung in Python

# illustrating public members & public access modifier 
class pub_mod:
    # constructor
    def __init__(self, name, age):
        self.name = name;
        self.age = age;
 
    def Age(self): 
        # accessing public data member 
        print("Age: ", self.age)
# creating object 
obj = pub_mod("Jason", 35);
# accessing public data member 
print("Name: ", obj.name)  
# calling public member function of the class 
obj.Age()
codelearner

Ähnliche Antworten wie “Programm zur Demonstration der Kapselung in Python”

Fragen ähnlich wie “Programm zur Demonstration der Kapselung in Python”

Weitere verwandte Antworten zu “Programm zur Demonstration der Kapselung in Python” auf Python

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen