", self. ) S=Sample() S.display() print("Value = ", S.n1) print("Value = ", S. ) Example : Program to illustrate private and public variables In the above program, there are two class variables n1 and n2 are declared. The variable n1 is a public variable and n2 is a private variable.
The display( ) member method is defined to show the values passed to these two variables. The print statements defined within class will successfully display the values of n1 and n2, even though the class variable n2 is private. Because, in this case, n2 is called by a method defined inside the class. But, when we try to access the value of n2 from outside the class Python throws an error.
Because, private variable cannot be accessed from outside the class. Output Class variable = Class variable = Value = Traceback (most recent call last): File "D:/Python/Class-Test- .py", line , in <module> print("Value = ", S. ) AttributeError: 'Sample' object has no attribute ' ' 12th Computer Chapter - - Python Classes and Objects . Sample Programs to illustrate classes and objects class Circle: pi= .
def (self,radius): self.radius=radius def area(self): return Circle.pi*(self.radius** ) def circumference(self): return *Circle.pi*self.radius r=int(input("Enter Radius: ")) C=Circle(r) print("The Area =",C.area()) print("The Circumference =", C.circumference()) Output: Enter Radius: The Area = . The Circumference = .400000000000002 Program : Write a program to calculate area and circumference of a circle class String: def (self): self.upper= self.lower= self.vowel= self.consonant= self.space= self.string="" def getstr(self): self.string=str(input("Enter a String: ")) def count (self): for ch in self.string: if (ch.isupper()): self.upper+= if (ch.islower()): self.lower+= if (ch in ('AEIOUaeiou'): self.vowel+= Program : Write a program to accept a string and print the number of uppercase, lowercase, vowels, consonants and spaces in the given string 12th Computer Chapter - - if (ch.isspace()): self.space+= self.consonant = self.upper+self.lower - self. vowel def display(self): print("The given string contains...") print("%d Uppercase letters"%self.upper) print("%d Lowercase letters"%self.lower) print("%d Vowels"%self.vowel) print("%d Consonants"%self.consonant) print("%d Spaces"%self.space) S = String() S.getstr() S.count() S.display() Output: Enter a String:Welcome To Learn Computer Science The given