Monday, 17 April 2017

adding and removing the attributes of a class




  • i can add the attributes and also removing the attributes in any programming languages.

    attributes means static variables(class variable) and non-static variables or object or instance variables.   
     
    Note:
     
    out side the class, we can add the static variables to the class is not possible in Java and .Net. it is possible in Python. 

    Adding the attributes to the class:

    Adding the static and non-static variables to the class and objects.

    We can add the static variables to the class from outside of the class by using class name.

    We can add the non-static variables to the object  from outside of the class by using reference variable.

    The non-static variables which are added to one object cannot access to the other object.

    class X:
        a=10
        def __init__(self):
            self.b=20
    print(X.a)
    x1=X()
    print(x1.b)
    X.c=30
    print(X.c)
    x1.d=40
    print(x1.d)
    x2=X()
    print(x2.b)
    x2.e=50
    print(x2.e)
     
    10
    20
    30
    40
    20
    50
     
    Remove the attributes from the class: 
     
    Deleting the static variables and non-static variables from the class and object:-

    We can remove the static and non-static variables from the class and object by using del keyword

    class X:   
        a=10
        b=20
        def __init__(self):
            self.c=30
            self.d=40
    print(X.a)
    print(X.b)
    x1=X()
    print(x1.c)
    print(x1.d)
    x2=X()
    print(x2.c)
    print(x2.d)
    del X.a
    print(X.b)
    del x1.c
    print(x1.d)
    print(x2.c)
    print(x2.d)

    10
    20
    30
    40
    30
    40
    20
    40
    30
    40


     

No comments:

Post a Comment