欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2.5

程序员文章站 2022-03-26 13:40:35
...

2.5

python

#访问限制
bart=Student('Bart Simpson',59)
#修改
bart.score=99
#实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问
class Student(object):
    def _init_(self,name,score):
        self._name=name
        self.score=score
        def get_name(self):
            return self._name
        def get_score(self):
            return self._score
        def set_score(self,score):
            if 0 <=score <=100:
                self._score=score
            else:
                raise  ValueError('bad score')
        def print_score(self):
            print('%s,%s'%(self._name,self._score))
bart = Student('Bart Simpson', 59)
print('bart.get_name()=',bart.get_name())
bart.set_score(60)
print('bart.getscore()=',bart.get_score())
#继承和多态
class Animal(object):
    def run(self):
        print('Animal is running')
class Dog(Animal):
 def run(self):
  print('Dog is running')
 def eat(self):
     print('Eating meat')
     #可以稍作改动
     class Dog(Animal):
         def run(self):
             print('Dog is running')
      c=Dog()
     isinstance(c,Dog)#True
     print('c is Animal?',isinstance(c,Animal))
     isinstance(c,Animal)#True

     #理解多态
     def run_twice(animal):
         animal.run()
     class   Tortoise(Animal):
         def run(self):
             print('Tortoise is running slowly')


 class Animal(object):
     def run(self):
         print("Animal is running")
     class Dog(Animal):
         pass
         class Cat(Animal):
             def run(self):
                 print('Cat is running')
                 pass
     class Car(object):
     def run(self):
     print('Car is runnng')
     class Stone(object):
         pass
     def run_twice(animal):
         animal.run()
         run_twice(Stone())
         #AttributeError: 'Stone' object has no attribute 'run'

c

  #include<stdio.h>
  int main()
  {
  	int fun(int x,int y,int(*p)(int,int));
  	int max(int,int);
  	int min(int,int);
  	int add(int,int);
  	int a=34,b=-21,n;
  	printf("please choose 1,2 or 3:");
  	scanf("%d",&n);
  	if(n==1) fun(a,b,max);
  	else if(n==2) fun(a,b,min);
  	else if(n==3) fun(a,b,add);
  	return 0;
   } 
   int fun(int x,int y,int(*p)(int,int))//声明形参p是指向函数的指针 
   {    //输入1时调用fun作为实参将两个整数传给fun  还将max作为实参传给形参p 
   	int result;
   	result=(*p)(x,y);
   	printf("%d\n",result);
   }
 int max(int x,int y)
 {
 	int z;
 	if(x>y)z=x;
 	else z=y;
 	printf("max=");
 	return(z);
 }
 int min(int x,int y)
 {
 	int z;
 	if(x<y)
 	z=x;
 	else
 	z=y;
 	printf("max=");
 	return(z);
 }
 int add(int x,int y)
 {
 	int z;
 z=x+y
 printf("sum=");
 return